package sessionbeans;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.*;

import com.sun.org.apache.commons.collections.Factory;

import dtofactory.FactoryDTO;

import entities.*;
import entitiesdto.*;
import sessionbeans.AdminArticulos;

@Stateless 
public class AdminArticulosBean implements AdminArticulos {

	@PersistenceContext
	private EntityManager manager;
	private FactoryDTO dtoFactory;
	
	public AdminArticulosBean(){
		dtoFactory=FactoryDTO.getInstance();
	}
	
	public boolean ingresarNuevoArticulo(ArticuloDTO art) {
//		
//		List<CantidadMateriaPrimaDTO> cmpList = art.getCantidadMateriasPrimas();
//		for(int i=0; i<cmpList.size();i++){
//			CantidadMateriaPrimaDTO cmpdto = cmpList.get(i);
//			CantidadMateriaPrima cmp = dtoFactory.dtoToCmp(cmpdto);
//			MateriaPrima mp = cmp.getMateriaPrima();
//			manager.persist(mp);
//			manager.persist(cmp);
//		}
		
		if (art instanceof HogarDTO) {
			Hogar artHogar = (Hogar) dtoFactory.dtoToArt(art);
			manager.persist(artHogar);
		} else {
			if (art instanceof RopaDTO) {
				Ropa artRopa = (Ropa) dtoFactory.dtoToArt(art);
				manager.persist(artRopa);
			}
		}
		return true;		
	}



	@SuppressWarnings("unchecked")
	public List<MateriaPrimaDTO> getMateriasPrimas() {
		List<MateriaPrima> mp = manager.createQuery("select m from MateriaPrima m").getResultList();
		ArrayList<MateriaPrimaDTO> result = new ArrayList<MateriaPrimaDTO>();
		for(MateriaPrima mater : mp){
			MateriaPrimaDTO material= FactoryDTO.getInstance().mpToDto(mater);
			result.add(material);
		}
		return result;
	}

	@Override
	public ArticuloDTO getArticulofromRef(String ref) {
		Articulo a = manager.find(Articulo.class, ref);
		return dtoFactory.artToDto(a);
	}




}
